/*
 * Copyright (C) 2020 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.sj.parksdk.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sj.parksdk.ParkSdk;
import com.sj.parksdk.R;
import com.sj.parksdk.activity.ParkSdkMainActivity;
import com.sj.parksdk.core.webview.AgentWebActivity;
import com.sj.parksdk.setting.Constans;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.file.FileIOUtils;
import com.xuexiang.xutil.file.FileUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import static com.sj.parksdk.core.webview.AgentWebFragment.KEY_URL;

/**
 * 工具类
 *
 * @author xuexiang
 * @since 2020-02-23 15:12
 */
public final class Utils {

    private Utils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 这里填写你的应用隐私政策网页地址
     */
    private static final String PRIVACY_URL = "https://gitee.com/xuexiangjys/TemplateAppProject/raw/master/LICENSE";

    /**
     * 显示隐私政策的提示
     *
     * @param context
     * @return
     */

    public static SweetAlertDialog showPrivacyDialog(Context context,SweetAlertDialog.OnSweetClickListener confirmClick){
        SweetAlertDialog sDailog = new SweetAlertDialog(context,SweetAlertDialog.CONFIRM_TYPE)
                .setTitleText(ResUtils.getString(R.string.sdialog_privacy_title))
                .setConfirmContentSpannable(getPrivacyContent(context))
                .setConfirmText(ResUtils.getString(R.string.lab_agree))
                .setConfirmClickListener(confirmClick)
                .setCancelText(ResUtils.getString(R.string.sdialog_privacy_refused))
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();

//                        XUtil.exitApp();
                    }
                });
        sDailog.setCanceledOnTouchOutside(false);
        sDailog.show();
        return sDailog;
    }

    /**
     * @return 隐私政策说明
     */
    private static SpannableStringBuilder getPrivacyContent(Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder()
                .append("亲爱的用户，感谢你对智慧停车的支持!在使用之前，请务必审慎阅读、充分理解")
                .append(getPrivacyLink(context,ResUtils.getString(R.string.login_server_agreement), Constans.API_AGREEMENT))
                .append("与")
                .append(getPrivacyLink(context, ResUtils.getString(R.string.login_privacy_agreement), Constans.PRIVACY_AGREEMENT))
                .append("各条款,我们将在征求你的同意后获取提供服务所需的相关信息，如当你使用位置相关的服务时,我们需要获取设备所在的位置信息。如你同意协议内容，请击“同意”开始使用。" );
        return stringBuilder;
    }

    /**
     * @param context 隐私政策的链接
     * @return
     */
    private static SpannableString getPrivacyLink(Context context,String name, String privacyUrl) {
        String privacyName = name;
        SpannableString spannableString = new SpannableString(privacyName);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                goWeb(context, privacyUrl);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setColor(ResUtils.getColor(R.color.app_color_theme_main));
                ds.setUnderlineText(false);
            }
        }, 0, privacyName.length(), Spanned.SPAN_MARK_MARK);
        return spannableString;
    }


    /**
     * 请求浏览器
     *
     * @param url
     */
    public static void goWeb(Context context, final String url) {
        Intent intent = new Intent(context, AgentWebActivity.class);
        intent.putExtra(KEY_URL, url);
        context.startActivity(intent);
    }


    /**
     * 是否是深色的颜色
     *
     * @param color
     * @return
     */
    public static boolean isColorDark(@ColorInt int color) {
        double darkness =
                1
                        - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color))
                        / 255;
        return darkness >= 0.382;
    }

    public static FlexboxLayoutManager getFlexboxLayoutManager(Context context) {
        //设置布局管理器
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(context);
        //flexDirection 属性决定主轴的方向（即项目的排列方向）。类似 LinearLayout 的 vertical 和 horizontal:
        // 主轴为水平方向，起点在左端。
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //flexWrap 默认情况下 Flex 跟 LinearLayout 一样，都是不带换行排列的，但是flexWrap属性可以支持换行排列:
        // 按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //justifyContent 属性定义了项目在主轴上的对齐方式:
        // 交叉轴的起点对齐
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        return flexboxLayoutManager;
    }


    /**
     * 同步首页状态,未启动就启动
     */
    public static void syncMainPageStatus() {
        if (!XUtil.getActivityLifecycleHelper().isActivityExist(ParkSdkMainActivity.class)) {
            ActivityUtils.startActivity(ParkSdkMainActivity.class);
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     */
    public static void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static Spanned getPriceHtml(String price,int format) {
//        if(StringUtils.isEmpty(price))price = "0.0";
////        String formatPrice ="¥ " + new BigDecimal(price).setScale(1, BigDecimal.ROUND_HALF_UP).toString();
//        String formatPrice ="¥" + price;
//        SpannableString spannableString = new SpannableString(formatPrice);
//        spannableString.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannableString.setSpan(new RelativeSizeSpan(0.6f), formatPrice.length()-3, formatPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        StringBuffer sb = new StringBuffer();
        sb.append("<small>¥ </small>")
                .append("<big>")
                .append(new BigDecimal(price).setScale(format, BigDecimal.ROUND_HALF_UP).toString())
                .append("</big>");
        return Html.fromHtml(sb.toString());
//        return spannableString;
    }

    public static Map<String, String> url2Map(String url) {
        Map<String, String> map = null;
        if(!url.contains("?"))return null;
        String paramStr = url.substring(url.indexOf("?"));
        if(!(paramStr.length()>1))return null;
        String params = paramStr.substring(1);
        if(!params.contains("&") || !params.contains("="))return null;
        String [] arr = params.split("&");
        map = new HashMap<String, String>();
        for (String str:arr) {
            String [] kv = str.split("=");
            map.put(kv[0],kv[1]);
        }
        return map;
    }

    public static String getUrlParam(String url, String name) {
        Map<String, String> map = url2Map(url);
        return map == null?"":map.get(name);
    }

    /**
     * 获取图片选择的配置
     *
     * @param fragment
     * @return
     */
    public static PictureSelectionModel getPictureSelector(Fragment fragment) {
        return PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.XUIPictureStyle)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .previewEggs(true);
    }

    //==========拍照===========//

    public static final String JPEG = ".jpeg";

    /**
     * 处理拍照的回调
     *
     * @param data
     * @return
     */
    public static String handleOnPictureTaken(byte[] data) {
        return handleOnPictureTaken(data, JPEG);
    }

    /**
     * 处理拍照的回调
     *
     * @param data
     * @return
     */
    public static String handleOnPictureTaken(byte[] data, String fileSuffix) {
        String picPath = FileUtils.getDiskCacheDir() + "/images/" + DateUtils.getNowMills() + fileSuffix;
        boolean result = FileIOUtils.writeFileFromBytesByStream(picPath, data);
        return result ? picPath : "";
    }

    /**
     * 获取屏幕宽
     */
    public static int getWindowWidth() {
        WindowManager wm = (WindowManager) ParkSdk.getContext()
                .getSystemService(Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取屏幕高
     */
    public static int getWindowHeight() {
        WindowManager wm = (WindowManager) ParkSdk.getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * @param str
     * @return
     */
    public static String encryptionStr(String str,int length){
        if(StringUtils.isEmpty(str))return str;
        if(!(str.length()>length))return str;
        int start = (str.length()-length)/2;
        int end = str.length()-start-1;
        String encryStr = "";
        for (int i =0;i <length;i++){
            encryStr +="*";
        }
        String startStr = start == 0?"": str.substring(0,start);
        String endStr = end == str.length()?"":str.substring(end,str.length());
        return startStr+encryStr+endStr;
    }


}
